
package com.tools.cleanmaster.model.cloud;

import com.tools.cleanmaster.model.item.PathUpdateInfo;
import com.tools.cleanmaster.model.language.LanguageCompat;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.RSACoder;
import com.tools.cleanmaster.utils.StringCompress;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TrashPostBodyUtils {

    /**
     * 生成数据库检查更新的请求 Body
     */
    public static String getPostBodyDB(String version, long updatatime) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(TrashPostContant.DB_VERSION, version);
            jsonObject.put(TrashPostContant.DB_UPTIME, updatatime);
        } catch (JSONException e) {
        }
        return jsonObject.toString();
    }

    /**
     * 生成已知路径请求更新的postBody
     */
    public static String getPostBodyCloudPath() {
        List<TrashCloudPathData.TrashFromCloud> trashCloudPathDatas = TrashCloudPathData.getInstance()
                .getTrashFromCloudByBunch();
        // 如果没有数据了就返回空
        if (trashCloudPathDatas == null || trashCloudPathDatas.size() <= 0) {
            return null;
        }
        JSONArray trashCloudPathJsonArray = new JSONArray();
        for (TrashCloudPathData.TrashFromCloud trashFromCloud : trashCloudPathDatas) {
            JSONObject object = new JSONObject();
            try {
                object.put(TrashPostContant.PATHID, trashFromCloud.mPathIdString);
                object.put(TrashPostContant.UPDATE_TIME, trashFromCloud.mUpdateTime);
                trashCloudPathJsonArray.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return trashCloudPathJsonArray.toString();
    }

    /**
     * 生成未知路径请求查询的Body
     */
    public static String getPostBodyUnKnowPath(List<TrashUnknowPathData.NormalPath> normalList,
                                               List<TrashUnknowPathData.NormalPath> androidDataList) {
        if (normalList.size() == 0 && androidDataList.size() == 0) {
            return null;
        }

        JSONArray resultArray = new JSONArray();

        if (androidDataList.size() > 0) {
            String encryptAndroidString = RSACoder.encryptByPublicKey(
                    TrashPostContant.ANDROID_PATH, TrashPostContant.publicKEY);
            String encryptDataString = RSACoder.encryptByPublicKey(TrashPostContant.DATA_PATH,
                    TrashPostContant.publicKEY);

            JSONObject androidDataJsonObject = new JSONObject();
            String androidDataJsonObject_Key = "|" + encryptAndroidString + "|" + encryptDataString;
            JSONArray androidDataJsonObject_Value = new JSONArray();
            try {
                for (TrashUnknowPathData.NormalPath androidPath : androidDataList) {
                    String encryptOne = RSACoder.encryptByPublicKey(androidPath.mLevelOne,
                            TrashPostContant.publicKEY);
                    if (androidPath.mLevelOne != null && androidPath.mLevelTwo != null) {
                        String encryptTwo = RSACoder.encryptByPublicKey(androidPath.mLevelTwo,
                                TrashPostContant.publicKEY);
                        androidDataJsonObject_Value.put("|" + encryptOne + "|" + encryptTwo);
                    } else if (androidPath.mLevelOne != null) {
                        androidDataJsonObject_Value.put("|" + encryptOne);
                    }
                }
                androidDataJsonObject.put(androidDataJsonObject_Key, androidDataJsonObject_Value);
                resultArray.put(androidDataJsonObject);
            } catch (JSONException e) {
            }
        }

        Map<String, List<String>> allNomalPathMap = new HashMap<String, List<String>>();
        for (TrashUnknowPathData.NormalPath normalPath : normalList) {
            if (normalPath.mLevelOne == null) {
                continue;
            }
            String allNomalPathMap_Key = "|" + RSACoder.encryptByPublicKey(normalPath.mLevelOne,
                    TrashPostContant.publicKEY);

            List<String> allNomalPathMap_Value = allNomalPathMap.get(allNomalPathMap_Key);
            if (allNomalPathMap_Value == null) {
                allNomalPathMap_Value = new ArrayList<String>();
            }
            String encryptTwo = null;
            String encryptThree = null;
            if (normalPath.mLevelThree != null && normalPath.mLevelTwo != null) {
                encryptTwo = RSACoder.encryptByPublicKey(normalPath.mLevelTwo,
                        TrashPostContant.publicKEY);
                encryptThree = RSACoder.encryptByPublicKey(normalPath.mLevelThree,
                        TrashPostContant.publicKEY);
                allNomalPathMap_Value.add("|" + encryptTwo + "|" + encryptThree);
            } else if (normalPath.mLevelTwo != null) {
                encryptTwo = RSACoder.encryptByPublicKey(normalPath.mLevelTwo,
                        TrashPostContant.publicKEY);
                allNomalPathMap_Value.add("|" + encryptTwo);
            }
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "请求路径=/" + normalPath.mLevelOne
                        + "/" + normalPath.mLevelTwo + "/" + normalPath.mLevelThree
                        + ",加密后的路径 = |" + allNomalPathMap_Key + "|" + encryptTwo + "|"
                        + encryptThree);
            }
            allNomalPathMap.put(allNomalPathMap_Key, allNomalPathMap_Value);
        }

        java.util.Iterator it = allNomalPathMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String keyString = (String) entry.getKey();
            JSONObject pathObject = new JSONObject();
            JSONArray valueArray = new JSONArray();
            List<String> list = (List<String>) entry.getValue();
            for (String string : list) {
                valueArray.put(string);
            }
            try {
                pathObject.put(keyString, valueArray);
                resultArray.put(pathObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String result = resultArray.toString();
        result = result.replace("\\", "");
        return result;
    }

    private static List<PathUpdateInfo> parseResponseJson(String returnArray, String lan) {
        if (returnArray == null) {
            return null;
        }
        List<PathUpdateInfo> pathUpdateInfos = new ArrayList<PathUpdateInfo>();
        try {
            JSONArray array = new JSONArray(returnArray);
            int length = array.length();
            for (int i = 0; i < length; i++) {
                JSONObject object = array.getJSONObject(i);
                PathUpdateInfo info = new PathUpdateInfo();
                info.pathId = object.optString(TrashPostContant.PATHID);
                info.type = object.optInt(TrashPostContant.TYPE);
                if (info.type == TrashPostContant.DELETE) {
                    pathUpdateInfos.add(info);
                    continue;
                } else {
                    info.desc = object.optString(TrashPostContant.DESC);
                    info.descID = object.optLong(TrashPostContant.DESC_ID);
                    info.localDesc = object.optString(TrashPostContant.LOCAL_DESC);
                    info.localLid = LanguageCompat.getLocaleID(lan);
                    info.updateTime = object.optLong(TrashPostContant.UPDATE_TIME);
                    info.inst_desc = object.optString(TrashPostContant.INST_DESC);
                    info.inst_sugg = object.optInt(TrashPostContant.INST_SUGG);
                    info.lid = object.optInt(TrashPostContant.LID, 1);//默认希望是英语
                    info.path = object.optString(TrashPostContant.TOTAL_PATH);
                    info.unin_desc = object.optString(TrashPostContant.UNIN_DESC);
                    info.unin_sugg = object.optInt(TrashPostContant.UNIN_SUGG);
                    JSONArray pkgArray = object.optJSONArray(TrashPostContant.PKG_INFO);

                    if (pkgArray != null && pkgArray.length() > 0) {
                        for (int j = 0; j < pkgArray.length(); j++) {
                            JSONObject packageJsonObject = pkgArray.getJSONObject(j);
                            String appName = packageJsonObject.optString(TrashPostContant.APP_NAME);
                            String pkg = packageJsonObject.optString(TrashPostContant.PKG_NAME);
                            PathUpdateInfo.DescriptionPackage descriptionPackage = info.getPkgInstance();
                            descriptionPackage.mPkg = pkg;
                            descriptionPackage.mAppName = appName;
                            info.pkgs.add(descriptionPackage);
                        }
                    }
                }
                pathUpdateInfos.add(info);
            }
        } catch (Exception exception) {
            return null;
        }
        if (TrashPostContant.OPEN) {
            int i = 1;
            for (PathUpdateInfo pathUpdateInfo : pathUpdateInfos) {
                {
                    LogHelper.i(TrashPostContant.TAG, "解析出来的数据 ，第" + i + "条" + " ，内容：" + pathUpdateInfo.toString());
                    i++;
                }
            }
        }
        return pathUpdateInfos;
    }

    private static String decryptResponseContent(String content) {
        if (content == null) {
            return null;
        }
        char[] responseDecode = StringCompress.enCodeStringByXOr(content,
                "我是Token");
        String responseDecodeStr = new String(responseDecode);
        return responseDecodeStr;
    }

    public static List<PathUpdateInfo> handleTrashData(String data, String lan) {
        String jsonArray = decryptResponseContent(data);
        if (TrashPostContant.OPEN) {
            LogHelper.i(TrashPostContant.TAG, "数据解密 ：" + jsonArray);
        }
        return parseResponseJson(jsonArray, lan);
    }
}
